How to copy complete structure in a byte array (character buffer) in C language?

Here, we will learn how to copy complete structure into a character array (byte array) in C programming language?

Such kind of requirement may occur many times, when you want to write a complete buffer into the memory or keep the data save into a character buffer.

In the given example, there is a structure Person with two members name and age, we will assign the values while declaring the structure variable person.

We will copy structure person into a character array (byte array) buffer and then print the value of buffer, since buffer will contain the unprintable characters, so we are printing Hexadecimal values of all bytes.

Let's consider the example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Person
{
	char name[20];
	int age;
};

int main()
{
	//structure variable declaratio with initialisation
	struct Person person={"Deniss Ritchie", 60};
	//declare character buffer (byte array)
	unsigned char *buffer=(char*)malloc(sizeof(person));
	int i;
	
	//copying....
	memcpy(buffer,(const unsigned char*)&person,sizeof(person));
	
	//printing..
	printf("Copied byte array is:\n");
	for(i=0;i<sizeof(person);i++)
		printf("%02X ",buffer[i]);
	printf("\n");
	
	//freeing memory..
	free(buffer);
	return 0;
}

Output

Copied byte array is:
44 65 6E 69 73 73 20 52 69 74 63 68 69 65 00 00 00 00 00 00 3C 00 00 00

Let's understand the output

name has 20 bytes and here is the value from buffer

44 65 6E 69 73 73 20 52 69 74 63 68 69 65 00 00 00 00 00 00

age has 4 bytes and here is the value from buffer

3C 00 00 00

(Here 3C is the Hexadecimal value of 60)


Related Tutorials




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.